<template>
  <div class="icons">
    <div class="icons-container">
      <div class="icons-inner">
        <a v-for="(item,index) in iconsList" :key="index">
          <img :src="item.imgUrl">
          <span>{{item.title}}</span>
        </a>
      </div>
    </div>

    <div class="bg-bottom">
      <div class="bottom-inner" :style="innerStyle"></div>
    </div>
  </div>
</template>

<script>
import {mapState,mapActions} from "vuex";
export default {
  data() {
    return {
      screen: document.documentElement.clientWidth || document.body.clientWidth,
      //可视区域点宽度,
      docWidth: 750,
      //文档宽度
      bottomWidth: 100,
      //灰色盒子宽度
      innerWidth: 0,
      //红色盒子宽度
      startX: 0, //  起点
      endX: 0, //  结束点
      moveX: 0 // 移动多少？
    };
  },
  mounted() {
    this.getBottomWidth();
    this.bindEvent();
    this.getIconsList()
  },
  methods: {
    ...mapActions(['getIconsList']),
    getBottomWidth() {
      this.innerWidth = (this.screen / this.docWidth) * this.bottomWidth;
    },
    bindEvent() {
      this.$el.addEventListener("touchstart", this.touchStart, false);
      this.$el.addEventListener("touchmove", this.touchMove, false);
      this.$el.addEventListener("touchend", this.touchEnd, false);
    },
    touchStart(event) {
      let touch = event.touches[0];
      this.startX = touch.pageX;
      //起点
    },
    touchMove(event) {
      let touch = event.touches[0];
      let left = touch.pageX - this.startX;
      //移动的点

      this.moveX = -((this.bottomWidth / this.screen) * left - this.endX);

      // （灰色 / 可视）：算出来比例       * 移动距离

      if (this.moveX < 0) {
        this.moveX = 0;
      } else if (this.moveX > this.bottomWidth - this.innerWidth) {
        this.moveX = this.bottomWidth - this.innerWidth;
      }
    },
    touchEnd() {
      this.endX = this.moveX;
    }
  },
  computed: {
    ...mapState(['iconsList']),
    innerStyle() {
      return {
        width: `${this.innerWidth}px`,
        left: `${this.moveX}px`
      };
    }
  }
};
</script>

<style scoped>
.icons {
  position: relative;
  width: 100%;
  height: 200px;
  border-top: 1px solid #ccc;
}
.icons-container {
  overflow-x: scroll;
  padding: 20px 0;
}
.icons-inner {
  width: 750px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}
.icons-inner a {
  display: flex;
  flex-direction: column;
  width: 73px;
  height: 60px;
  justify-content: center;
  align-items: center;
}
.icons-inner img {
  width: 39px;
  height: 39px;
}

.icons-container::-webkit-scrollbar {
  display: none;
}
.bg-bottom {
  width: 100px;
  height: 2px;
  background: #ccc;
  position: absolute;
  bottom: 20px;
  left: 50%;
  margin-left: -50px;
}
.bottom-inner {
  position: absolute;
  bottom: 0;
  left: 0;
  background: red;
  height: 100%;
  width: 25px;
}
a{
  margin-top:10px
}
</style>
